package com.example.wm.config;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.wm.entity.EmployeeManagement;
import com.example.wm.entity.Productunpacking;
import com.example.wm.service.EmployedManageService;
import com.example.wm.service.ProductunpackingService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class ScheduledNotificationService {

    @Resource
    private ProductunpackingService productunpackingService;

    @Resource
    private EmployedManageService employedManageService;

    // 每天下午6点执行
//    @Scheduled(cron = "0 * * * * ?")
    @Scheduled(cron = "0 0 18 * * ?")
    public void sendDailyNotification() {
        try {
            // 获取今日有拆解的人的姓名，并且通知
            LambdaQueryWrapper<Productunpacking> lq = new LambdaQueryWrapper<>();

            // 添加今天的时间范围查询
            LocalDate today = LocalDate.now();
            LocalDateTime startOfDay = today.atStartOfDay(); // 00:00:00
            LocalDateTime endOfDay = today.atTime(23, 59, 59); // 23:59:59
            lq.between(Productunpacking::getInserttime, startOfDay, endOfDay);

            List<Productunpacking> list = productunpackingService.list(lq);

            // 获取所有不重复的 addname
            Set<String> addnamelist = list.stream()
                    .map(Productunpacking::getAddname)
                    .collect(Collectors.toSet());

            // 发送通知
            for (String addname : addnamelist) {
                try {
                    // 查询openid
                    LambdaQueryWrapper<EmployeeManagement> lq2 = new LambdaQueryWrapper<>();
                    lq2.eq(EmployeeManagement::getLoginname, addname);
                    EmployeeManagement employee = employedManageService.getOne(lq2);

                    if (employee != null && employee.getWeixinopenid() != null) {
                        String touser = employee.getWeixinopenid();

                        // 创建data数据
                        Map<String, String> dataMap = new HashMap<>();
                        dataMap.put("thing2", addname);
                        dataMap.put("thing8", "今日拆解数据日报提醒");
                        dataMap.put("time10", String.valueOf(today));

                        // 调用微信通知接口
                        sendWeChatNotification(touser, dataMap, addname);

                        // 添加日志记录
                        System.out.println("已发送通知给: " + addname + " 时间: " + LocalDateTime.now());
                    }
                } catch (Exception e) {
                    System.err.println("发送通知给 " + addname + " 失败: " + e.getMessage());
                }
            }

        } catch (Exception e) {
            System.err.println("定时任务执行失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 发送微信通知
     */
    /**
     * 发送微信通知
     */
    private void sendWeChatNotification(String touser, Map<String, String> dataMap, String addname) {
        try {
            String template_id = "EX37GpmWsHGfYUihuzqXQykit7jtTQyd2WeK7Ji7LGg";
            String lang = "zh_CN";
//formal developer
            String miniprogram_state = "formal";
            String page = "subpkg/Tender/TenderTadyData/TenderTadyData?addname=" + addname;

            // 构建正确的微信模板消息格式
            Map<String, Object> requestParam = new HashMap<>();
            requestParam.put("template_id", template_id);
            requestParam.put("touser", touser);
            requestParam.put("page", page);
            requestParam.put("miniprogram_state", miniprogram_state);
            requestParam.put("lang", lang);

            // 微信模板消息要求 data 字段必须是特定格式
            Map<String, Object> data = new HashMap<>();
            data.put("thing2", new HashMap<String, String>() {{
                put("value", addname);
            }});
            data.put("thing8", new HashMap<String, String>() {{
                put("value", "今日拆解数据日报提醒");
            }});
            data.put("time10", new HashMap<String, String>() {{
                put("value", LocalDate.now().toString());
            }});

            requestParam.put("data", data);

            // 调用微信接口发送通知
            String result = callWeChatAPI(requestParam);
            System.out.println("微信通知发送结果: " + result);

        } catch (Exception e) {
            System.err.println("发送微信通知失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    /**
     * 调用微信API
     */
    private String callWeChatAPI(Map<String, Object> requestParam) {
        try {
            // 获取access_token
            String accessToken = getAccessToken();

            String baseUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken;

            String jsonStr = JSONUtil.toJsonStr(requestParam);

            HttpResponse response = HttpRequest.post(baseUrl)
                    .header(Header.CONTENT_ENCODING, "UTF-8")
                    .header(Header.CONTENT_TYPE, "application/json")
                    .body(jsonStr)
                    .execute();

            if (response.getStatus() == HttpStatus.HTTP_OK) {
                return response.body();
            }

        } catch (Exception e) {
            System.err.println("调用微信API失败: " + e.getMessage());
        }

        return "发送失败";
    }

    /**
     * 获取微信access_token
     */
    private String getAccessToken() {
        try {
            CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?appid=wxba6a21693d6b5a99&secret=836e5643d37955fbaa32894a8614c60e&grant_type=client_credential";

            HttpGet httpGet = new HttpGet(accessUrl);
            CloseableHttpResponse res = httpClient.execute(httpGet);
            HttpEntity responseEntity = res.getEntity();
            String resultDemo = EntityUtils.toString(responseEntity);

            JSONObject json = JSONObject.parseObject(resultDemo);
            return json.getString("access_token");

        } catch (Exception e) {
            System.err.println("获取access_token失败: " + e.getMessage());
            return null;
        }
    }
}